package cool.zhoujie.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public abstract class BaseLazyLoadFragment extends Fragment {

    private boolean isFirstLoad = false;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = initView(inflater, container);
        initEvent();//初始化事件
        isFirstLoad = true;//视图创建完成，将变量置为true
        if (getUserVisibleHint()) {
            //如果fragment可见，进行数据加载
            onLazyLoad();
            isFirstLoad = false;
        }
        return view;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //视图销毁，将变量置为false
        isFirstLoad = false;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isFirstLoad && isVisibleToUser) {
            //视图变为可见，并且是第一次加载
            onLazyLoad();
            isFirstLoad = false;
        }
    }

    //初始化视图接口，留给子类实现
    public abstract View initView(LayoutInflater inflater, ViewGroup container);

    //初始化事件接口，留给子类实现
    public abstract void initEvent();

    //数据加载接口，留给子类实现
    public abstract void onLazyLoad();
}
